package middleware

import (
	"fx_swift_api/internal/model"
	"fx_swift_api/pkg/code"
	"fx_swift_api/pkg/global"
	"github.com/gin-gonic/gin"
	"net/http"
)

func CheckAuth() gin.HandlerFunc {
	var (
		agentObj *model.FxAgent
		err      error
	)
	return func(c *gin.Context) {
		// 获取token
		appId := c.Request.Header.Get("appId")
		appSecret := c.Request.Header.Get("appSecret")
		if len(appId) > 0 && len(appSecret) > 0 {
			if err = global.GFDB.Model("fx_agent").
				Where("app_id=? and app_secret=?", appId, appSecret).Scan(&agentObj); err != nil || agentObj == nil {
				code.Fail(c, http.StatusUnauthorized, code.ErrInvalidAuthHeader, "header must have appId and appSecret")
				c.Abort()
				return
			}
			// 将Token信息存入上下文
			c.Set("Account", agentObj.Account)
		}
		c.Next()
	}
}
